package dataStructure.others;

/**
 * Description 针对26个字母的字典树
 *
 * @ClassName dataStructure.others.TrieTree
 * @Version 1.0
 * @Date: 2022/2/18 16:07
 * @Author xuyi
 */
public class TrieTree {
    public class Node1{
        public int pass;
        public int end;
        public Node1[] next;

        public Node1() {
            pass = 0;
            end = 0;
            next = new Node1[26];
        }
    }

    public class Trie1{
        public Node1 root;

        public Trie1() {
            root = new Node1();
        }

        public void insert(String word){
            if(word == null||word.equals("")){
                return;
            }
            Node1 node = root;
            node.pass++;
            char[] chars = word.toCharArray();
            int idx;
            for(int i=0;i<chars.length;i++){
                idx=chars[i]-'a';
                if(node.next[idx]==null){
                    node.next[idx] = new Node1();
                }
                node = node.next[idx];
                node.pass++;
            }
            node.end++;
        }

        public void delete(String word){
            if(search(word)==0){
                return;
            }
            Node1 node = root;
            node.pass--;
            char[] chars = word.toCharArray();
            int idx;
            for(int i=0;i<chars.length;i++){
                idx = chars[i]-'a';
                if(--node.next[idx].pass==0){
                    node.next[idx]=null;
                    return;
                }
                node = node.next[idx];
            }
            node.end--;
        }

        /**
         * 查找指定字符串在前缀树中出现的次数
         */
        public int search(String word){
            if(word==null||word.equals("")){
                return 0;
            }
            Node1 node = root;
            char[] chars = word.toCharArray();
            int idx;
            for(int i=0;i<chars.length;i++){
                idx = chars[i]-'a';
                if(node.next[idx]==null){
                    return 0;
                }
                node = node.next[idx];
            }
            return node.end;
        }

        // 所有加入的字符串中，有几个是以pre这个字符串作为前缀的
        public int prefixNumber(String pre) {
            if (pre == null) {
                return 0;
            }
            char[] chs = pre.toCharArray();
            Node1 node = root;
            int index = 0;
            for (int i = 0; i < chs.length; i++) {
                index = chs[i] - 'a';
                // 走不到最后，就没有
                if (node.next[index] == null) {
                    return 0;
                }
                node = node.next[index];
            }
            // 顺利走到最后，返回的pass就是有多少个字符串以当前pre为前缀的
            return node.pass;
        }

    }
}
